//获取应用实例
const app = getApp()
const innerAudioContext = wx.createInnerAudioContext()

Page({
    data: {
      showConfirm:false,
      boxId:"",
      report:{},
      reportId:"",
      score_item:'',
      raw_fileUrls:[],
      resourceIndex:0,
      tempFilePath:"",
      isShowSubmit:false,
      playAudioShow:false,
      text:"播放",
      text:"",
      isCloseCheck:false,
      is_open_ai:false
    },
    handleSuccess:function(e){
      const { files } = e.detail;
      console.log('files',files)
      // this.setData({
      //   originFiles: files,
      // });
    },
    handleClick(e) {
      console.log(e.detail.file);
    },

    onLoad: function(options) {
      if (options != null){
        const boxId= options.boxId;
        const score_item= options.score_item;
        this.setData({boxId,score_item});
        this.getBox(boxId)
        var that = this;
        wx.request({
          url: app.globalData.url+'/wechat/student_report',
          data: {
            username: app.globalData.localuserinfo.username,
            boxId,
            score_item
          },
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          success: res2 => {
            const raw_fileUrls=res2.data&&res2.data.raw_fileUrls||[];
            const image=raw_fileUrls.find(f=>f.type==="image");
            const video=raw_fileUrls.find(f=>f.type==="video");
            const dataInfo=raw_fileUrls.find(f=>f.type==="text");
            this.setData({
              report:res2.data||{},
              raw_fileUrls:raw_fileUrls,
              imageUrl:image&&image.url,
              videoUrl:video&&video.url,
              reportId:res2.data&&res2.data.objectId,
              text:dataInfo&&dataInfo.data
            });
            wx.setNavigationBarTitle({
              title: score_item
          })
          }
        })
        
      }
    },
    getBox:function(boxId){
      const score_item=this.data.score_item;
    
      wx.request({
        url: app.globalData.url+'/wechat/box?boxId='+boxId,
        method: 'get',
        success: res2 => {
        const box=res2.data||{};
        const score_item_options=box.score_item_options||{};
        const score_item_option=score_item_options[score_item]||{};
        const isCloseCheck=score_item_option.isCloseCheck||false;
        const is_open_ai=box.is_ai_score_open||false;
        this.setData({is_open_ai,isCloseCheck}) 
        }
      })
    },

    showDeleteVideoConfirm:function(){
      if(this.data.report.r_score||this.data.isCloseCheck){
        wx.showModal({
          title: '提示',
          content: '作业批改或者关闭之后不可以删除！',
          success: (res) => {

          }
        });
        return;
      }
      wx.showModal({
        title: '提示',
        content: '确定删除该视频？',
        success: (res) => {
          if (res.confirm) {
            this.removeResource('video')
          }
        }
      })
    },
    playRecordAudio() {
      //在ios下静音时播放没有声音，默认为true，改为false就好了。
      innerAudioContext.obeyMuteSwitch = false
        this.setData({
          text: "播放中",
        })
        innerAudioContext.src = this.data.report.audio_url
        innerAudioContext.play()
        innerAudioContext.onEnded(() => {
          this.setData({
            text: '播放',
          })
        })
    },

    showDialog:function(e){
      const index=e.target.id
      this.setData({showConfirm:true,resourceIndex:index})
    },
    closeDialog:function(){
      this.setData({showConfirm:false})
    },

    onChange:function(e){
      console.log("onChange")
    },

    addImage:function(){
      const that=this;
      wx.chooseMedia({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        mediaType:["image"],
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFile = res.tempFiles[0];
          that.setData({tempFilePath:tempFile.tempFilePath});
          that.upload(tempFile.tempFilePath,tempFile.fileType)
        },
      })
    },
    addVideo:function(){
      const that=this;
      wx.chooseMedia({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        mediaType:["video"],
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFile = res.tempFiles[0];
          that.setData({tempFilePath:tempFile.tempFilePath});
          that.upload(tempFile.tempFilePath,tempFile.fileType)
        },
      })
    },

    upload:function(tempFilePath,type){
      const that=this;
      wx.request({
        url: app.globalData.url + '/wechat/qiniu_upload_token',
        method: 'get',
        success: res => {
          const uploadTask = wx.uploadFile({
            url: res.data.url,
            header: { 'content-type': 'multipart/form-data' },
            method: 'POST',
            filePath: tempFilePath,
            name: 'file',
            formData: {
              'token': res.data.upload_token
            },
            success: function (res2) {
              const data = JSON.parse(res2.data);
              const fileurl=res.data.qiniu_domain+data.key;
              const raw_fileUrls=that.data.raw_fileUrls;
              raw_fileUrls.push({type,url:fileurl});
             wx.request({
                url: app.globalData.url+'/wechat/update_report',
                data: {
                  id: that.data.reportId,
                  key:"raw_fileUrls",
                  value:raw_fileUrls,
                  token:app.globalData.token,
            },
            method: 'POST',
             header: {
              'content-type': 'application/json'
             },
            success: res2 => {
              switch (type) {
                case "image": {
                  console.log("fileurl",fileurl)
                  that.setData({
                    imageUrl:fileurl,
                });
                const is_open_ai=that.data.is_open_ai;
                if(is_open_ai){
                  that.startAIScore(fileurl)
                }
                    break;
                }
                
                case "video": {
                  that.setData({
                    videoUrl:fileurl,
                });
                    break;
                }
    
            }
              that.setData({
                report:res2.data||{},
                raw_fileUrls,
            });
          }
        })
            },
            fail: function (err) {
              wx.showToast({
                title: '上传失败，图片服务器出错：' + err.errMsg,
                icon: 'none',
                duration: 2000
              })
            },
          })
          uploadTask.onProgressUpdate((res) => {
            if (res.progress == 100) {
              wx.showToast({
                title: '上传成功！',
                icon: 'success',
                duration: 2000
              })
            }
          })
        },
        fail: function (err) {
          console.log(err);
          wx.showToast({
            title: '上传失败，获取token出错：' + err,
            icon: 'none',
            duration: 2000
          })
        }
      });
    },

    startAIScore:function(fileUrl){ 
      wx.request({ 
        url: app.globalData.url+'/wechat/start_image_ai_score', 
        method: 'post', 
        data:{ 
          fileUrl, 
          reportId:this.data.reportId, 
          boxId:this.data.boxId 
        }, 
        success: res2 => { 
        }}) 
     
    }, 
  
    showDeleteImageConfirm:function(){
      if(this.data.report.r_score||this.data.isCloseCheck){
        wx.showModal({
          title: '提示',
          content: '作业批改或者关闭之后不可以删除！',
          success: (res) => {
          }
        });
        return;
      }
      wx.showModal({
        title: '提示',
        content: '确定删除该图片？',
        success: (res) => {
          if (res.confirm) {
            this.removeResource('image')
          }
        }
      })
    },

    removeResource:function(type){
      const that=this;
      const raw_fileUrls=this.data.raw_fileUrls;
      const _raw_fileUrls= raw_fileUrls.filter(f=>f.type!==type);
      wx.request({
        url: app.globalData.url+'/wechat/update_report',
        data: {
          id: that.data.reportId,
          key:"raw_fileUrls",
          value:_raw_fileUrls,
          token:app.globalData.token
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: res2 => {
          switch (type) {
            case "image": {
              this.setData({
                imageUrl:"",
            });
                break;
            }
            case "video": {
              this.setData({
                videoUrl:"",
            });
                break;
            }

        }
          this.setData({
            // report:res2.data||{},
            raw_fileUrls:_raw_fileUrls,
          });
        }
      })
    },
    upResource:function(e){
      const that=this;
      const idx=e.target.id;
      const raw_fileUrls=this.data.raw_fileUrls;
      if (idx <= 0) {
        return;
    }
    const oResource=raw_fileUrls[idx];
    raw_fileUrls.splice(idx, 1);//删除原id
    raw_fileUrls.splice(idx - 1, 0, oResource);
    wx.request({
      url: app.globalData.url+'/wechat/update_report',
      data: {
        id: that.data.reportId,
        key:"raw_fileUrls",
        value:raw_fileUrls,
        token:app.globalData.token
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: res2 => {
        this.setData({
          report:res2.data||{},
          raw_fileUrls:raw_fileUrls,
          showConfirm:false
        });
      }
    })
    },
    downResource:function(e){
      const that=this;
      const idx=e.target.id;
      const raw_fileUrls=this.data.raw_fileUrls
        if (idx >= raw_fileUrls.length - 1) {
            return;
        }
        const oResource=raw_fileUrls[idx];
        raw_fileUrls.splice(idx, 1);//删除原id
        raw_fileUrls.splice(idx + 1, 0, oResource);
        wx.request({
          url: app.globalData.url+'/wechat/update_report',
          data: {
            id: that.data.reportId,
            key:"raw_fileUrls",
            value:raw_fileUrls,
            token:app.globalData.token
          },
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          success: res2 => {
            this.setData({
              report:res2.data||{},
              raw_fileUrls:raw_fileUrls,
              showConfirm:false
            });
          }
        })
    },
    changeText:function(e){
      this.setData({text:e.detail.value})
    },

    saveText:function(e){
      const raw_fileUrls=this.data.raw_fileUrls;
      const data={type:"text",data:this.data.text};
      raw_fileUrls.push(data)
      wx.request({
        url: app.globalData.url+'/wechat/update_report',
        data: {
          id: this.data.reportId,
          key:"raw_fileUrls",
          value:raw_fileUrls,
          token:app.globalData.token
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: res2 => {
          this.setData({
            report:res2.data||{},
            raw_fileUrls:raw_fileUrls,
          });
          wx.navigateBack()
        }
      })
    },
    closeSubmit:function(){
      this.setData({isShowSubmit:false})
    },
    showSubmit:function(){
      this.setData({isShowSubmit:true})
    },
    submitReport:function(){
      const that=this;
      wx.request({
        url: app.globalData.url+'/wechat/update_report',
        data: {
          id: that.data.reportId,
          key:"status",
          value:'已提交/未批改',
          token:app.globalData.token
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: res2 => {
          wx.navigateTo({
            url:"../student_m_report_box/student_m_report_box?boxId="+this.data.boxId
        });
        }
      })
    },
    onUnload: function () {
      // wx.reLaunch({
      //   url: "../student_m_report_box/student_m_report_box?boxId="+this.data.boxId,
      // })
  },

  
})
